Skip to content

feat(textarea): add autoGrow, height and maxHeight props #588#593

Merged
airikej merged 3 commits into
rcfrom
feat/588-textarea-add-expandable-height-and-change-min-height
Apr 15, 2026
Merged

feat(textarea): add autoGrow, height and maxHeight props #588#593
airikej merged 3 commits into
rcfrom
feat/588-textarea-add-expandable-height-and-change-min-height

Conversation

@airikej
Copy link
Copy Markdown
Contributor

@airikej airikej commented Apr 8, 2026

Summary by CodeRabbit

  • New Features

    • Auto-grow textarea that adjusts height with configurable min/max rows and optional max-height.
  • Style

    • Improved textarea sizing and typography; full-width box-sizing and right-aligned character counter. Added an auto-grow modifier that changes overflow/resize behavior.
  • Tests

    • Expanded tests covering auto-grow behavior, height constraints, character counter, disabled/helper/validation states.
  • Documentation

    • New story showcasing height and auto-grow examples.

@airikej airikej linked an issue Apr 8, 2026 that may be closed by this pull request
21 tasks
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 8, 2026

Warning

Rate limit exceeded

@airikej has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 33 minutes and 19 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 33 minutes and 19 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ae5ac06d-e9d0-4543-8be9-859c3d407bcc

📥 Commits

Reviewing files that changed from the base of the PR and between 28d8cf7 and 723eda7.

📒 Files selected for processing (1)
  • src/tedi/components/form/textarea/textarea.tsx
📝 Walkthrough

Walkthrough

Adds auto-grow capability and height controls to the TextArea component, including new props (autoGrow, minRows, maxRows, height, maxHeight), height-calculation logic, styling modifier, expanded tests, and a new story demonstrating height scenarios.

Changes

Cohort / File(s) Summary
Component Logic
src/tedi/components/form/textarea/textarea.tsx
Added props autoGrow, minRows, maxRows, height, maxHeight. Implemented refs/effects and a height-calculation flow that sets style.height and toggles overflowY when autoGrow is enabled; updates on mount and value changes.
Styling
src/tedi/components/form/textarea/textarea.module.scss
Adjusted base textarea styling (box-sizing: border-box, width: 100%, line-height: 1.5), added &--auto-grow modifier (overflow-y: auto, resize: none), and right-aligned character count.
Tests
src/tedi/components/form/textarea/textarea.spec.tsx
Reworked test suite: added auto-grow behavior tests (minRows→rows, async height changes, maxRows→scrolling, maxHeight handling), preserved/reintroduced tests for disabled/helper text/validation, and adjusted controlled onChange assertions.
Stories
src/tedi/components/form/textarea/textarea.stories.tsx
Removed padding-14-16 from some state rows; added TemplateHeights and exported HeightExamples story showing fixed height, custom height, autoGrow with min/max rows, and maxHeight-constrained examples.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant Component as TextArea Component
    participant Native as DOM Textarea
    participant Calc as Height Calculator

    User->>Component: Mount with props (autoGrow?, minRows, maxRows, height, maxHeight)
    Component->>Native: Attach ref to native textarea element
    Component->>Calc: Request initial height calculation
    Calc->>Native: Read computedStyle (line-height/padding) and scrollHeight
    Calc-->>Component: Return calculated height & overflow decision
    Component->>Native: Apply style.height and style.overflowY (or maxHeight)

    User->>Native: Type text
    Native->>Component: onChange / value update
    Component->>Calc: Recalculate height
    Calc->>Native: Measure new scrollHeight
    Calc-->>Component: Return updated height (clamped by maxRows/maxHeight)
    Component->>Native: Update style.height and overflowY

    alt Exceeds maxRows or maxHeight
        Component->>Native: Set overflow-y: auto (enable scrolling)
    else Within bounds
        Component->>Native: Keep overflow hidden (auto-grow)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I nibble lines until it grows,

rows unfurl where content flows.
Min and max keep balance sweet,
overflow dances with every beat.
Hooray — a textarea that hops to meet! 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately describes the main changes: adding autoGrow, height, and maxHeight props to the textarea component, which is the primary focus across all modified files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/588-textarea-add-expandable-height-and-change-min-height

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 8, 2026

Codecov Report

❌ Patch coverage is 92.30769% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/tedi/components/form/textarea/textarea.tsx 92.30% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/tedi/components/form/textarea/textarea.tsx (2)

109-121: Redundant useEffect hooks for height calculation.

Both effects call calculateHeight() when autoGrow is true:

  • Lines 109-115: Triggers on value change with requestAnimationFrame
  • Lines 117-121: Triggers on mount/dependency change synchronously

The second effect (117-121) is largely redundant since handleRef (line 137) already calls calculateHeight() on mount via setTimeout. Additionally, the first effect already covers value changes.

♻️ Consolidate into a single effect
  useEffect(() => {
    if (autoGrow) {
      requestAnimationFrame(() => {
        calculateHeight();
      });
    }
  }, [value, autoGrow, calculateHeight]);

- useEffect(() => {
-   if (autoGrow && textareaRef.current) {
-     calculateHeight();
-   }
- }, [autoGrow, calculateHeight]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tedi/components/form/textarea/textarea.tsx` around lines 109 - 121,
Remove the redundant useEffect that synchronously calls calculateHeight (the one
which depends on [autoGrow, calculateHeight]) and consolidate height logic into
a single effect: keep the existing effect that watches [value, autoGrow,
calculateHeight] and uses requestAnimationFrame to call calculateHeight for
value changes and initial mount; ensure initial mount is still covered (you can
call calculateHeight via requestAnimationFrame when autoGrow is true and
textareaRef.current exists). This touches calculateHeight, textareaRef,
handleRef, autoGrow, value, requestAnimationFrame and setTimeout (leave
handleRef’s setTimeout as-is or remove its calculateHeight call if you fully
rely on the consolidated effect).

60-60: Unused textareaHeight state creates unnecessary complexity.

The textareaHeight state (line 60) and the effect that updates it (lines 166-175) are disconnected from the actual height management. The calculateHeight function directly mutates textarea.style.height (line 98), bypassing React state entirely. Meanwhile, customInputProps uses textareaHeight which starts as 'auto' and only gets updated after the DOM mutation.

This creates:

  1. An unnecessary re-render cycle when textareaHeight state updates
  2. A brief moment where customInputProps provides height: 'auto' before syncing

Consider simplifying by either:

  • Removing the textareaHeight state and relying solely on direct DOM manipulation (current approach already works this way)
  • Or using state-driven height exclusively and removing the direct style.height assignments
♻️ Simplified approach: remove unused state
- const [textareaHeight, setTextareaHeight] = React.useState<string | number>('auto');
  const customInputProps = React.useMemo(() => {
    if (autoGrow) {
      return {
        rows: minRows,
        style: {
          ...(maxHeight ? { maxHeight } : {}),
          overflow: 'hidden',
-         height: textareaHeight,
        },
      };
    } else {
      // ... non-autoGrow case
    }
- }, [autoGrow, minRows, maxHeight, height, textareaHeight]);
+ }, [autoGrow, minRows, maxHeight, height]);
- useEffect(() => {
-   if (autoGrow && textareaRef.current) {
-     const updateHeight = () => {
-       if (textareaRef.current) {
-         setTextareaHeight(textareaRef.current.style.height);
-       }
-     };
-     updateHeight();
-   }
- }, [autoGrow, value]);

Also applies to: 144-175

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tedi/components/form/textarea/textarea.tsx` at line 60, Remove the unused
React state and effect: delete the textareaHeight state declaration and any
calls to setTextareaHeight, and remove the effect that updates textareaHeight
(which references calculateHeight). Update customInputProps to stop using
textareaHeight for the height prop so it no longer supplies height:'auto' (let
calculateHeight continue to set textarea.style.height directly). Ensure
calculateHeight remains and is invoked where it was before (e.g., on
input/change and mount) so the textarea height is managed solely via direct DOM
mutation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/tedi/components/form/textarea/textarea.spec.tsx`:
- Around line 96-120: The test mutates
HTMLTextAreaElement.prototype.scrollHeight but never restores it, causing
cross-test pollution; update the tests that set Object.defineProperty(...,
'scrollHeight', ...) (the one asserting rows/autoGrow and the 'respects maxRows
and enables scroll when exceeded with autoGrow' test) to save the original
descriptor (e.g., const originalScrollHeight =
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'scrollHeight')),
then after the test restore it with
Object.defineProperty(HTMLTextAreaElement.prototype, 'scrollHeight',
originalScrollHeight) (or delete the property if original was undefined), and
ensure restoration runs in a finally/afterEach block so the prototype is always
cleaned up.

In `@src/tedi/components/form/textarea/textarea.tsx`:
- Around line 154-157: The else branch of the textarea rendering still sets
rows: minRows even when autoGrow is false, which contradicts the prop docs;
update the non-autoGrow branch in textarea.tsx (the logic around autoGrow and
minRows) to avoid forcing rows to minRows — only set rows when autoGrow is true
(or when an explicit rows prop is provided), and remove or conditionally guard
the rows: minRows assignment so the native textarea sizing/explicit rows prop
behavior is preserved; ensure this change touches the same function/return block
that currently references autoGrow and minRows.
- Around line 83-84: The code calls parseFloat(computedStyle.lineHeight) which
can be NaN when line-height is "normal"; update the logic in the textarea height
calculation (where computedStyle and lineHeight are used in the Textarea
component) to detect NaN and fall back to a sensible numeric value (for example
parseFloat(computedStyle.fontSize) * 1.5, or a hardcoded default like 24) before
using lineHeight in height calculations so the resize logic never receives NaN.

---

Nitpick comments:
In `@src/tedi/components/form/textarea/textarea.tsx`:
- Around line 109-121: Remove the redundant useEffect that synchronously calls
calculateHeight (the one which depends on [autoGrow, calculateHeight]) and
consolidate height logic into a single effect: keep the existing effect that
watches [value, autoGrow, calculateHeight] and uses requestAnimationFrame to
call calculateHeight for value changes and initial mount; ensure initial mount
is still covered (you can call calculateHeight via requestAnimationFrame when
autoGrow is true and textareaRef.current exists). This touches calculateHeight,
textareaRef, handleRef, autoGrow, value, requestAnimationFrame and setTimeout
(leave handleRef’s setTimeout as-is or remove its calculateHeight call if you
fully rely on the consolidated effect).
- Line 60: Remove the unused React state and effect: delete the textareaHeight
state declaration and any calls to setTextareaHeight, and remove the effect that
updates textareaHeight (which references calculateHeight). Update
customInputProps to stop using textareaHeight for the height prop so it no
longer supplies height:'auto' (let calculateHeight continue to set
textarea.style.height directly). Ensure calculateHeight remains and is invoked
where it was before (e.g., on input/change and mount) so the textarea height is
managed solely via direct DOM mutation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ae34fff9-1e09-4112-8147-6fb20508439d

📥 Commits

Reviewing files that changed from the base of the PR and between 8233427 and 71d7699.

📒 Files selected for processing (4)
  • src/tedi/components/form/textarea/textarea.module.scss
  • src/tedi/components/form/textarea/textarea.spec.tsx
  • src/tedi/components/form/textarea/textarea.stories.tsx
  • src/tedi/components/form/textarea/textarea.tsx

Comment thread src/tedi/components/form/textarea/textarea.spec.tsx
Comment thread src/tedi/components/form/textarea/textarea.tsx Outdated
Comment thread src/tedi/components/form/textarea/textarea.tsx
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (1)
src/tedi/components/form/textarea/textarea.spec.tsx (1)

89-127: ⚠️ Potential issue | 🟡 Minor

Always restore the global mocks, even on failure.

These tests still patch window.getComputedStyle, and the second one also overrides HTMLTextAreaElement.prototype.scrollHeight, without guaranteed cleanup. If an assertion or user.type() throws, later tests inherit the patched globals and become flaky; the second test never restores scrollHeight at all.

🧹 Suggested cleanup pattern
   it('grows height when typing with autoGrow=true', async () => {
     const user = userEvent.setup();
-    const originalGetComputedStyle = window.getComputedStyle;
-    window.getComputedStyle = jest.fn().mockImplementation((el) => ({
-      ...originalGetComputedStyle(el),
-      lineHeight: '20px',
-      paddingTop: '8px',
-      paddingBottom: '8px',
-    }));
-
     const originalScrollHeightDescriptor = Object.getOwnPropertyDescriptor(
       HTMLTextAreaElement.prototype,
       'scrollHeight'
     );
-    Object.defineProperty(HTMLTextAreaElement.prototype, 'scrollHeight', {
-      configurable: true,
-      get() {
-        return 100 + (this.value.split('\n').length - 1) * 40;
-      },
-    });
-
-    render(<TextArea {...defaultProps} autoGrow minRows={3} maxRows={10} />);
-    ...
-
-    window.getComputedStyle = originalGetComputedStyle;
-    if (originalScrollHeightDescriptor) {
-      Object.defineProperty(HTMLTextAreaElement.prototype, 'scrollHeight', originalScrollHeightDescriptor);
-    } else {
-      delete (HTMLTextAreaElement.prototype as UnknownType).scrollHeight;
-    }
+    const originalGetComputedStyle = window.getComputedStyle;
+
+    try {
+      window.getComputedStyle = jest.fn().mockImplementation((el) => ({
+        ...originalGetComputedStyle(el),
+        lineHeight: '20px',
+        paddingTop: '8px',
+        paddingBottom: '8px',
+      }));
+
+      Object.defineProperty(HTMLTextAreaElement.prototype, 'scrollHeight', {
+        configurable: true,
+        get() {
+          return 100 + (this.value.split('\n').length - 1) * 40;
+        },
+      });
+
+      render(<TextArea {...defaultProps} autoGrow minRows={3} maxRows={10} />);
+      ...
+    } finally {
+      window.getComputedStyle = originalGetComputedStyle;
+      if (originalScrollHeightDescriptor) {
+        Object.defineProperty(HTMLTextAreaElement.prototype, 'scrollHeight', originalScrollHeightDescriptor);
+      } else {
+        delete (HTMLTextAreaElement.prototype as UnknownType).scrollHeight;
+      }
+    }
   });

Apply the same try/finally restoration to the maxRows test.

Also applies to: 133-166

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tedi/components/form/textarea/textarea.spec.tsx` around lines 89 - 127,
The test patches window.getComputedStyle and
HTMLTextAreaElement.prototype.scrollHeight but does not guarantee restoration on
failure; wrap the setup and assertions in a try/finally in the TextArea
autoGrow/maxRows tests so the original window.getComputedStyle and
originalScrollHeightDescriptor are restored in the finally block; locate the
test that calls render(<TextArea {...defaultProps} autoGrow minRows={3}
maxRows={10} />) and the other maxRows test and move the mocking of
getComputedStyle and Object.defineProperty for scrollHeight into the try section
and perform window.getComputedStyle = originalGetComputedStyle and restore
HTMLTextAreaElement.prototype.scrollHeight (using originalScrollHeightDescriptor
or delete fallback) inside finally to ensure cleanup even if assertions or
user.type() throw.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/tedi/components/form/textarea/textarea.tsx`:
- Around line 74-121: calculateHeight currently mutates the DOM height directly
while the rendered height comes from textareaHeight state, causing races where
requestAnimationFrame snapshots stale inline styles and textfield.tsx later
re-applies the old input.style.height; instead, make calculateHeight compute the
new height but set the textareaHeight state (the single source of truth) rather
than writing textarea.style.height, and update any overflow tweaks via state or
derived props; also remove or stop copying the current textarea inline style
back into textareaHeight later (the code that reads input.style.height and
re-spreads it in textfield.tsx) so only textareaHeight drives the rendered
height and useEffect simply calls calculateHeight which updates that state.
- Around line 35-37: Update the JSDoc for the maxHeight prop to reflect actual
behavior: state that maxHeight controls the element's CSS max-height both when
autoGrow is true and when a fixed height is used, rather than saying it's only
for autoGrow; find the maxHeight prop in the Textarea (or TextareaProps)
declaration and the block where styles are applied (the code that sets
style.maxHeight / style.height in the Textarea render/computeStyles logic) and
change the comment to mention both modes so generated prop docs match the
implementation.
- Around line 108-112: The current overflow toggle only checks rowCount against
maxRows which can leave content hidden if maxHeight is reached earlier; update
the logic in the auto-grow/adjustHeight routine that touches
textarea.style.overflowY (references: rowCount, maxRows, maxHeight, textarea) to
compute the intended content height (use textarea.scrollHeight or computed line
height * rowCount) and compare that against maxHeight — if the intended height
exceeds maxHeight set textarea.style.overflowY = 'auto' and enforce
textarea.style.maxHeight, otherwise set overflowY = 'hidden'. Apply the same
amended check where overflow is also handled later (the block that currently
sets maxHeight at lines 154-158) so both places use the computed-height vs
maxHeight comparison.

---

Duplicate comments:
In `@src/tedi/components/form/textarea/textarea.spec.tsx`:
- Around line 89-127: The test patches window.getComputedStyle and
HTMLTextAreaElement.prototype.scrollHeight but does not guarantee restoration on
failure; wrap the setup and assertions in a try/finally in the TextArea
autoGrow/maxRows tests so the original window.getComputedStyle and
originalScrollHeightDescriptor are restored in the finally block; locate the
test that calls render(<TextArea {...defaultProps} autoGrow minRows={3}
maxRows={10} />) and the other maxRows test and move the mocking of
getComputedStyle and Object.defineProperty for scrollHeight into the try section
and perform window.getComputedStyle = originalGetComputedStyle and restore
HTMLTextAreaElement.prototype.scrollHeight (using originalScrollHeightDescriptor
or delete fallback) inside finally to ensure cleanup even if assertions or
user.type() throw.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d0b2c829-1c28-4585-88bb-5bd4f5751cd9

📥 Commits

Reviewing files that changed from the base of the PR and between 71d7699 and 28d8cf7.

📒 Files selected for processing (2)
  • src/tedi/components/form/textarea/textarea.spec.tsx
  • src/tedi/components/form/textarea/textarea.tsx

Comment thread src/tedi/components/form/textarea/textarea.tsx
Comment thread src/tedi/components/form/textarea/textarea.tsx
Comment thread src/tedi/components/form/textarea/textarea.tsx Outdated
Comment thread src/tedi/components/form/textarea/textarea.tsx
@airikej airikej merged commit 2c86740 into rc Apr 15, 2026
20 checks passed
@airikej airikej deleted the feat/588-textarea-add-expandable-height-and-change-min-height branch April 15, 2026 10:00
github-actions Bot pushed a commit that referenced this pull request Apr 15, 2026
# [17.0.0-rc.5](react-17.0.0-rc.4...react-17.0.0-rc.5) (2026-04-15)

### Features

* **textarea:** add autoGrow, height and maxHeight props [#588](#588) ([#593](#593)) ([2c86740](2c86740))
github-actions Bot pushed a commit that referenced this pull request Apr 29, 2026
# [17.0.0](react-16.1.0...react-17.0.0) (2026-04-29)

### Bug Fixes

* **checkbox:** invalid indicator hover border fix [#605](#605) ([#609](#609)) ([f1d62c6](f1d62c6))
* **select:** select placeholder no longer blocks context menu interactions [#584](#584) ([#585](#585)) ([e8d86ab](e8d86ab))
* **variables:** update core version, update variable names [#592](#592) ([#598](#598)) ([1f15b36](1f15b36))

### Features

* **button-group:** add mobile variant [#448](#448) ([#606](#606)) ([54dee90](54dee90)), closes [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94) [#94](#94)
* **card:** add more control to borderRadius usage, add examples [#444](#444) ([#597](#597)) ([deac9db](deac9db))
* **print:** introduce PrintingProvider + context-based usePrint [#99](#99) ([#497](#497)) ([a58cb70](a58cb70))
* **spinner:** add new sizes [#586](#586) ([#589](#589)) ([fbea0c3](fbea0c3))
* **tabs:** new tedi-ready component [#555](#555) ([#557](#557)) ([9c06c51](9c06c51))
* **textarea:** add autoGrow, height and maxHeight props [#588](#588) ([#593](#593)) ([2c86740](2c86740))
* **toggle:** new TEDI-Ready component [#305](#305) ([#594](#594)) ([6f28045](6f28045))

### BREAKING CHANGES

* **print:** usePrint hook removed.
Replace with usePrint from the new PrintingProvider context.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Textarea]: Add expandable height and change min height

2 participants